#include "protol.hpp"
#include "Sock.hpp"
#include <mutex>
#include <cstdlib>
#include <cstring>

std::vector<char> idlist;
std::vector<char> friendlist;
int sockfd;
void *Routine(void *args)
{
    while (1)
    {
        char buff[1024] = {0};
        int ret = read(sockfd, buff, sizeof(buff));
        buff[ret] = '\0';
        if (buff[0] == '@')
        {
            idlist.push_back(buff[1]);
            std::cout << "friend applylist add:" << buff[1] << std::endl;
        }
        else if (buff[0] == '$')
        {
            friendlist.push_back(buff[1]);
            std::cout << "friend list add:" << buff[1] << std::endl;
        }
        else
        {
            std::cout << buff << std::endl;
        }
        
    }
}
int main()
{
    std::mutex mutex;
    Sock::Sock sock(8888, "0.0.0.0");
    sock.InitCli();
    sockfd = sock.get_sockfd();
    char buff[1024] = {0};

    int ret = read(sockfd, buff, sizeof(buff));
    std::cout << buff << std::endl;

    ProtoL proto;

    pthread_t ptd;
    pthread_create(&ptd, nullptr, Routine, nullptr);

    while (1)
    {
        std::cout << "choose your operator(1:addfriend 2:chat 3.getfriend):";
        int opt;
        std::cin >> opt;
        if (opt == 2)
        {
            std::cout << "you can chat with:";
            for (auto i : friendlist)
            {
                std::cout << i << " ";
            }
            int id;
            std::cout << "Chosen chat user:" << std::endl;
            std::cin >> id;
            std::cout << "you say:";
            std::string msg;
            std::cin >> msg;
            msg = proto.Selizer(id, msg);
            write(sockfd, msg.c_str(), msg.size());
            sleep(1);
        }
        else if (opt == 1)
        {
            int id;
            std::cout << "Chosen add user:" << std::endl;
            std::cin >> id;
            std::string msg = proto.selizer_addfriend(id);
            write(sockfd, msg.c_str(), msg.size());
        }
        else if (opt == 3)
        {
            std::cout << "you can process:";
            for (auto i : idlist)
            {
                std::cout << i << " ";
            }
            std::cout << "chosen id:";
            int id;
            std::cin >> id;
            std::string msg = proto.selizer_agreefriend(id);
            write(sockfd, msg.c_str(), msg.size());
        }
    }
    return 0;
}